import {Component, OnInit, ElementRef, Renderer, OnChanges} from '@angular/core';
import {Input} from "@angular/core/src/metadata/directives";
/**
 * {
   *  title: string,
   *  content: string,
   *  type: stiring [error | success | warning | info]
   * }
 */
@Component({
  selector: 'iotek-toast',
  templateUrl: './toast.component.html',
  styleUrls: ['./toast.component.less']
})
export class ToastComponent implements OnInit, OnChanges {
  /**
   * {
   *  title: string,
   *  content: string,
   *  type: stiring [error | success | warning | info]
   * }
   */
  @Input("toastConfig")
  public config;

  public timeLeft: number = 5000;
  private toastOverFlag = false;
  public toastShow = false;
  private interval;

  constructor(
    private ele: ElementRef,
    private render: Renderer
  ) {

  }

  ngOnInit() {
  }

  ngOnChanges(): void {
    if(!this.config || !this.config.title || !this.config.content) {
      this.toastShow = false
      return;
    }
    this.timeLeft = 5000;
    this.toastShow = true;
    this.interval = setInterval(()=>{
      if(!this.toastOverFlag) {
        this.timeLeft -= 10;
      }
      if(this.timeLeft <= 0) {
        clearInterval(this.interval);
      }
    }, 10);
  }

  public toastOver() {
    this.toastOverFlag = true;
  }

  public toastLeave() {
    this.toastOverFlag = false;
  }

  public getToastType() {
    var defaultCss = {
      'toast-success': false,
      'toast-warning': false,
      'toast-info': false,
      'toast-error': false,
    };
    defaultCss['toast-' + this.config.type] = true;
    return defaultCss;
  }
}
